<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" :width="1300" align-center>
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData.data"
      :rules="formRules"
      label-width="auto"
    >
      <el-row :gutter="16">
        <el-col :span="24">
          <el-form-item label="单位名称" prop="name">
            <el-input v-model="formData.data.name" placeholder="请输入单位名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位类型" prop="type">
            <el-select v-model="formData.data.type" clearable placeholder="请选择单位类型">
              <el-option
                v-for="dict in unitTypeList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.label"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="社会统一信用代码" prop="creditCode">
            <el-input v-model="formData.data.creditCode" placeholder="请输入社会统一信用代码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="formData.data.contactPerson" placeholder="请输入联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="formData.data.phone" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="法人代表" prop="legalRepresentative">
            <el-input v-model="formData.data.legalRepresentative" placeholder="请输入法人代表" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮政编码" prop="postalCode">
            <el-input v-model="formData.data.postalCode" placeholder="请输入邮政编码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="传真" prop="fax">
            <el-input v-model="formData.data.fax" placeholder="请输入传真" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="formData.data.address" placeholder="请输入详细地址" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资质情况">
            <div class="flex-s">
              <div class="upload_box flex-c">
                <el-upload
                  class="avatar_uploader flex-c"
                  :http-request="e => customRequest(e, 'companyImage')"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="formData.data.companyImage" :src="formData.data.companyImage" class="avatar" />
                  <el-icon v-else class="avatar_uploader-icon"><CameraFilled /></el-icon>
                </el-upload>
                <div class="uploader__text">公司图片</div>
              </div>

              <div class="upload_box flex-c">
                <el-upload
                  class="avatar_uploader flex-c"
                  :http-request="e => customRequest(e, 'businessLicense')"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="formData.data.businessLicense" :src="formData.data.businessLicense" class="avatar" />
                  <el-icon v-else class="avatar_uploader-icon"><CameraFilled /></el-icon>
                </el-upload>
                <div class="uploader__text">营业执照</div>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上传附件">
            <div class="upload_box" style="width: 100%;">
              <UploadFile
                v-model="formData.data.attachment"
                class="upload-demo"
                :http-request="e => customRequest(e, 'attachment')"
                :fileSize="20"
                :fileType="['jpg', 'png', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']"
                :limit="10"
              />
            
            
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table :data="formData.data.bankInfo">
      <el-table-column align="center" label="开户名称" prop="userName">
        <template #default="scope">
          <el-input v-if="scope.row.editable" v-model="scope.row.userName" placeholder="请输入开户名称" />
          <div v-else>{{ scope.row.userName }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="开户银行" prop="bankName">
        <template #default="scope">
          <el-input v-if="scope.row.editable" v-model="scope.row.bankName" placeholder="请输入开户银行" />
          <div v-else>{{ scope.row.bankName }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="银行账号" prop="bankAccount">
        <template #default="scope">
          <el-input v-if="scope.row.editable" v-model="scope.row.bankAccount" placeholder="请输入银行账号" />
          <div v-else>{{ scope.row.bankAccount }}</div>
        </template>
      </el-table-column>
      <el-table-column :width="200" align="center" label="操作">
        <template #default="scope">

          <div v-if="scope.row.editable">
            <el-button link type="info" @click="cancle(scope.$index)">取消</el-button>
            <el-button link type="primary" @click="save(scope.row, scope.$index)">保存</el-button>
          </div>
          <div v-else>
            <el-button link type="primary" @click="edit(scope.$index)">
              编辑
            </el-button>
            <el-popconfirm
              class="box-item"
              title="确定删除？"
              placement="top-end"
              @confirm="del(scope.$index)"
            >
              <template #reference>
                <el-button link type="danger">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>

    </el-table>

    <el-button class="addRow" @click="addRow" plain>
      <el-icon class="mr-6"><Plus /></el-icon>  添加
    </el-button>
    <template #footer>
      <el-button type="primary" @click="submitForm(0)">保 存</el-button>
      <el-button type="primary" @click="submitForm(1)">保存并提交</el-button>
      <el-button @click="dialogVisible = false;resetForm()">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup>
  import {ref,reactive} from "vue"
  import * as ContactApi from '@/api/viewsApi/contactUnits'
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import { Plus, CameraFilled } from '@element-plus/icons-vue'
  import { formRules } from './formRules'
  import { updateFile } from "@/api/infra/file/index.ts"
  import { UploadFile } from "@/components/UploadFile/index.ts"
  const unitTypeList = ref(getIntDictOptions(DICT_TYPE.UNIT_TYPE)) // 单位类型数据
  const { t } = useI18n() // 国际化
  const message = useMessage() // 消息弹窗
  const getList = inject('getList', () => {})
  const dialogVisible = ref(false) // 弹窗的是否展示
  const dialogTitle = ref('') // 弹窗的标题
  const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
  const formType = ref('') // 表单的类型：create - 新增；update - 修改
  const formData = reactive({
    data: {
      name: undefined,
      type: undefined,
      creditCode: undefined,
      contactPerson: undefined,
      phone: undefined,
      legalRepresentative: undefined,
      postalCode: undefined,
      fax: undefined,
      address: undefined,
      bankInfo: []
    },
  })
  let copyData = ref([])
  /**
   * 表格逻辑处理 - 开始
  */

  const addRow = () => {
    let bankList = JSON.parse(JSON.stringify(formData.data.bankInfo))
    copyData.value = JSON.parse(JSON.stringify(bankList))
    let flag = bankList.find(item => item.editable)
    if (flag) {
      message.warning('请先保存当前数据')
      return
    }
    bankList.push({
      userName: '',
      bankName: '',
      bankAccount: '',
      editable: true,
    })
    formData.data.bankInfo = bankList
  }

  const edit = (index) => {
    let bankInfo = JSON.parse(JSON.stringify(formData.data.bankInfo))
    let flag = bankInfo.find(item => item.editable)
    if (flag) {
      message.warning('请先保存当前数据')
      return
    }
    copyData.value = JSON.parse(JSON.stringify(bankInfo))
    console.log(copyData.value);
    bankInfo[index].editable = true
    formData.data.bankInfo = bankInfo
  }

  const del = (index) => {
    let bankInfo = JSON.parse(JSON.stringify(formData.data.bankInfo))
    bankInfo.splice(index, 1)
    formData.data.bankInfo = bankInfo
  }

  const cancle = () => {
    let bankInfo = JSON.parse(JSON.stringify(copyData.value))
    formData.data.bankInfo = bankInfo
  }

  const save = (row, index) => {
    let bankInfo = JSON.parse(JSON.stringify(formData.data.bankInfo))

    const {userName, bankName, bankAccount} = row
    if (!userName) {
      message.warning('请输入开户名称')
      return
    }
    if (!bankName) {
      message.warning('请输入开户银行')
      return
    }
    if (!bankAccount) {
      message.warning('请输入银行账号')
      return
    }
    bankInfo.forEach(item => item.editable = false)
    formData.data.bankInfo = bankInfo
  }

  /**
   * 表格逻辑处理 - 结束
   */



  /**
   * 图片上传逻辑 - 开始
   */

  const beforeAvatarUpload = (rawFile) => {
    let imgTypeList = ['image/jpeg', 'image/png', 'image/webp']
    if (!imgTypeList.includes(rawFile.type)) {
      ElMessage.error('请上传jpg、png、webp格式图片')
      return false
    } else if (rawFile.size / 1024 / 1024 > 20) {
      ElMessage.error('图片大小不能超过 20MB!')
      return false
    }
    return true
  }

  const customRequest = async (options, type) => {
    const upFilesData = new FormData()
    upFilesData.append('file', options.file)
    try {
      const res = await updateFile(upFilesData)
      if(type === 'attachment'){
        formData.data[type].push(res.data)
      }else{
        formData.data[type] = res.data
      }
    }finally {
      
    }
    
  }
  /**
   * 图片上传逻辑 - 结束
   */

  const formRef = ref() // 表单 Ref
  /** 打开弹窗 */
  const open = async (type, id) => {
    dialogVisible.value = true
    dialogTitle.value = t('action.' + type)
    formType.value = type
    resetForm()
    // 修改时，设置数据
    if (id) {
      formLoading.value = true
      try {
        formData.data = await ContactApi.getContactDetail(id)
      } finally {
        formLoading.value = false
      }
    }
  }
  defineExpose({ open })
  
  /**
   * 提交表单
   * */
  const submitForm = async (type) => {
    const formEl = formRef.value
    if (!formEl) return
    formEl.validate((valid, fields) => {
      if(valid){
        formLoading.value = true
        formData.data.status = type
        if (formType.value === 'create') {
          ContactApi.addContactl(formData.data).then(res => {
            getList()
            message.success('新增成功')
            dialogVisible.value = false
            resetForm()
          }).finally(() =>{
            formLoading.value = false
          })
        } else {
          ContactApi.editContactl(formData.data).then(res => {
            getList()
            message.success('编辑成功')
            dialogVisible.value = false
            resetForm()
          }).finally(() =>{
            formLoading.value = false
          })
        }
      }else{
        for(let key in fields){
          message.error(fields[key][0].message)
        }
      }
    })
  }

  /** 重置表单 */
  const resetForm = () => {
    formData.data = {
        name: undefined,
        type: undefined,
        creditCode: undefined,
        contactPerson: undefined,
        phone: undefined,
        legalRepresentative: undefined,
        postalCode: undefined,
        fax: undefined,
        address: undefined,
        bankInfo: []
    }
    formRef.value?.resetFields()
  }
</script>
<style lang="scss" scoped>
.upload_box{
  height: 230px;
  flex-direction: column;
  margin-left: 18px;
  .uploader__text{
    margin-top: 6px;
  }
}

.avatar_uploader {
  width: 180px;
  height: 100%;
  border: 1px dashed #999;
  color: #999;
  border-radius: 2px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  
  .avatar_uploader-icon {
    font-size: 28px;
    width: 180px;
    height: 230px;
    text-align: center;
  }

  img{
    width: 180px;
    height: 230px;
  }
}
.avatar_uploader:hover {
  border-color: #2568f8;
  color: #2568f8;
}
.addRow{
  margin-top: 12px;
  width: 100%;
}
::v-deep .el-upload-list{
  overflow-y: scroll;
  height: 160px;
}
// ::v-deep .fileName{
//   width: 285px;
// }
a {
  text-decoration: none;
}
</style>
